<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/27
 * Time: 15:38
 */

namespace app\admin\controller;


use app\common\controller\Backend;
use app\common\utils\Constant;
use think\Db;
use think\Exception;
use app\common\utils\PHPExcelUtils;
/**
 * 报事报修管理
 * Class Repair
 * @package app\admin\controller
 */
class Repair extends Backend
{
    protected $model = null;

    public function _initialize(){
        parent::_initialize();
        $this->model = model('Repair');
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $userId = $this->auth->id;
            $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
            $map = [];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if($user['user_type'] == Constant::USER_TYPE_PROPERTY) {
                $villageIds = $this->getVillageIds($user['property_id']);
                $map['village_id'] = array('in', $villageIds);
            }
            $total = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key => &$value){
                $value['user_nickname'] = model('User')->where("id={$value['user_id']}")->value('nickname');
                $value['village_name'] = model('Village')->where("id={$value['village_id']}")->value('name');
                $value['detail'] = model('HouseProperty')->where("id={$value['house_property_id']}")->value('detail');
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    public function deal(){
        $id = input('post.id');
        $userId = $this->auth->id;
        $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
        if(empty($id)){
            return json(return_data(Constant::CODE_ERROR, '参数错误'));
        }
        $repair = Db::name("repair")->where(array('id'=>$id))->find();
        if($repair['status'] != Constant::REPAIR_PROCESSING){
            return json(return_data(Constant::CODE_ERROR, '该报事保修无法处理'));
        }
        if($user['user_type'] == Constant::USER_TYPE_PROPERTY) {
            //获取报事报修的物业ID
            $propertyId = model('Village')->where("id={$repair['village_id']}")->value('property_id');
            if($user['property_id'] != $propertyId){
                return json(return_data(Constant::CODE_ERROR, '无权限'));
            }
        }
        //处理操作将状态设为已处理
        try{
            Db::startTrans();
            Db::name("repair")->where(array('id'=>$id))->update([
                'status'   =>    Constant::REPAIR_DEALED
            ]);
            Db::commit();
            return json(return_data(Constant::CODE_SUCCESS, '处理成功'));
        }catch (Exception $e){
            Db::rollback();
            return json(return_data(Constant::CODE_ERROR, $e->getMessage()));
        }
    }

    /**
     * 导出报事报修excel
     */
    public function exportRepair(){
        $ids = input('get.ids');
        $status = input('get.status');
        $villageId = input('get.village_id');
        $map = [];
        $userId = $this->auth->id;
        $user = model('User')->where(array('id'=>$userId))->field('user_type,property_id')->find();
        $villageIds = $this->getVillageIds($user['property_id']);
        if($user['user_type'] == Constant::USER_TYPE_PROPERTY && empty($villageId)) {
            $map['village_id'] = array('in', $villageIds);
        }
        else if($villageId && $user['user_type'] == Constant::USER_TYPE_PROPERTY){
            if(!in_array($villageId, $villageIds)){
                $this->error("参数错误");
            }
        }
        try {
            Db::startTrans();
            $phpExcelUtil = new PHPExcelUtils();
            $cellList = array('ID', '用户姓名','手机号', '小区名称', '地址', '详情');
            $obj = $phpExcelUtil->setCellList($cellList);
            $objSheet = $obj->getActiveSheet();
            $row = 2;
            if($ids) {
                $map['id'] = array('in', $ids);
                $list = $this->model->where($map)->select();
            }
            else{

                if(!empty($status) || $status == 0){
                    $map['status'] = $status;
                }
                if(!empty($villageId) && $villageId != 0){
                    $map['village_id'] = $villageId;
                }
                $list = $this->model->where($map)->select();
           /*     var_dump($this->model->getLastSql());
                exit();*/
            }
            $changeIds = [];
            foreach ($list as $key => $value) {
                if($value['status'] == Constant::REPAIR_DEAL_WAIT){
                    $changeIds[] = $value['id'];
                }
                $owner = model('Owner')->where("user_id={$value['user_id']}")->field('name,phone')->find();
                $villageName = model('Village')->where("id={$value['village_id']}")->value("name");
                $address = model('HouseProperty')->where("id={$value['house_property_id']}")->value('detail');
                $objSheet->setCellValue('A' . $row, $value['id']);
                $objSheet->setCellValue('B' . $row, $owner['name']);
                $objSheet->setCellValue('C' . $row, $owner['phone']);
                $objSheet->setCellValue('D' . $row, $villageName);
                $objSheet->setCellValue('E' . $row, $address);
                $objSheet->setCellValue('F' . $row, $value['remark']);
                $row++;
            }
            if(!empty($changeIds)){
                Db::name('repair')->where(array('id' => array('in', $changeIds)))->setField('status', Constant::REPAIR_PROCESSING);
            }
            $fileName = iconv("utf-8", "gb2312", date('Y-m-d', time()) . '-repair-list.xls');
            $obj->setActiveSheetIndex(0);
            header('Content-Type: application/vnd.ms-excel');
            header("Content-Disposition: attachment;filename=\"$fileName\"");
            header('Cache-Control: max-age=0');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel5');
            $objWriter->save('php://output'); //文件通过浏览器下载
            Db::commit();
            exit;
        }catch (\Exception $e){
            Db::rollback();
            echo $e->getMessage();
        }

    }


}